#!/bin/bash

if ! command -v dos2unix &> /dev/null
then
    apt install dos2unix &> /dev/null
fi



cd compiler

#if [ -e "build" ]; then
#    rm -r build
#fi

if [ ! -d "build" ]; then
  mkdir build
fi
cd build
touch ../../err.txt
cmake .. > ../../err.txt 2>&1 >/dev/null
make > ../../err.txt 2>&1 >/dev/null


if [ $? == 0 ]; then
  cd ../test-cases
  read -p '' case
  file=${case}
  filename="${file#./}"
  filename="${filename%.sy}"
#  echo "Compiling $filename ..."
  ../build/compiler "$filename.sy" -o "$filename.s" -S
  if ! riscv64-unknown-elf-gcc "$filename.s" ../runtime/src/sylib.c -iquote ../runtime/include -o "$filename.bin" --static ; then
    echo "生成目标代码有误"
    exit 0
  fi
  qemu-riscv64 -L /usr/bin "$filename.bin" < "$filename.in" > "$filename.out1" 2>/dev/null
  # ./"$filename" < "$filename.in" > "$filename.out"
  echo $? >> "$filename.out1"
  dos2unix "$filename.out1" 2>/dev/null
  dos2unix "$filename.out" 2>/dev/null
#    if ! diff "$filename.out1" "$filename.out" >/dev/null; then
  if ! diff "$filename.out1" "$filename.out" ; then
      echo "输出与预期结果不一致"
      exit 0
  fi
  rm "./$filename.bin" 2>&1 >/dev/null
  echo "PASS!"
  # rm *.s *.out1 2>&1 >/dev/null
  cd ../../
else
  echo "程序构建错误，提示信息如下："
  cd ../
  cat err.txt
fi